﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Application.ProductApp;
using JFnetcore.Models;
using Domain.Entities;
using Utility;
using Microsoft.AspNetCore.Http;
using System.Web;
using static Utility.FileUtil;
using System.IO;
using System.Net.Http.Headers;
using Application.LogApp;
using static Utility.EnumUtil;
using Application.ProductTypeApp;
using JFnetcore.Models.ViewModel;
using System.Text;
using Newtonsoft.Json;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace JFnetcore.Controllers
{
    public class ProductController : BaseController
    {
        private IProductAppService _productAppService;
        private IProductTypeAppService _producttypeAppService;
        private ILogAppService _logAppService;
        public ProductController(IProductAppService productAppService, ILogAppService logAppService, IProductTypeAppService producttypeAppService)
        {
            _productAppService = productAppService;
            _producttypeAppService = producttypeAppService;
            _logAppService = logAppService;
        }

        #region 软件中心

        #region 软件列表
        /// <summary>
        /// 打开产品下载列表视图
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult List(PageModel pagemodel)
        {
            //获取Session信息并且返回前台
            User userSession = getUserSession().User;
            

                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;
                ViewBag.AllRecords = _productAppService.GetAll(pagemodel.SearchKeyWords).Count;
                //ViewBag.Modellist = _productAppService.GetPageList(pagemodel.SearchKeyWords, int.Parse(pagemodel.PageSize), int.Parse(pagemodel.PageCurrent), pagemodel.OrderField, pagemodel.OrderDirection);


                List<Product> productlist = _productAppService.GetPageList(pagemodel.SearchKeyWords, int.Parse(pagemodel.PageSize), int.Parse(pagemodel.PageCurrent), pagemodel.OrderField, pagemodel.OrderDirection).ToList();
                List<ProductType> producttypelist = _producttypeAppService.GetAll("");
                ViewBag.Modellist = new CS.vProductHelp().GetVProductList(productlist, producttypelist);
                return View();
            
        }

        #endregion

        #region 类型管理
        /// <summary>
        /// 打开产品类型列表视图
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Type(PageModel pagemodel)
        {
            //获取Session信息并且返回前台
            User userSession = getUserSession().User;
            

                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;
                ViewBag.AllRecords = _producttypeAppService.GetAll(pagemodel.SearchKeyWords).Count;
                ViewBag.Modellist = _producttypeAppService.GetPageList(pagemodel.SearchKeyWords, int.Parse(pagemodel.PageSize), int.Parse(pagemodel.PageCurrent), pagemodel.OrderField, pagemodel.OrderDirection);

                return View();
            
        }


        /// <summary>
        /// 打开产品类型编辑视图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult TypeEdit(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return View();
            }
            else
            {
                var model = _producttypeAppService.GetById(Int32.Parse(id));
                return View(model);
            }

        }

        /// <summary>
        /// 表单提交产品类型编辑接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("ProductTypeEdit")]
        public IActionResult ProductEdit(ProductType model)
        {

            model.Createtime = DateTime.Now;
            if (_producttypeAppService.AddOrUpdate(model))
            {
                SessionModel sm = getUserSession();
                if (model.Id != 0)
                    _logAppService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.add, "新增产品类型 " + model.ProductType_name);
                else
                    _logAppService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.update, "修改产品类型 " + model.ProductType_name);

                return Content(ReturnJsonHelp.BJUIajaxJson(200, "提交成功！", "ProductType", "", "", true, "", ""));
            }
            else
            {
                return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败！", "", "", "", false, "", ""));
            }

        }

        public IActionResult TypeDelete(string id)
        {
            if (_productAppService.GetAll("").Where(i => i.ProductType_Id == Int32.Parse(id)).Count() > 0)
            {
                return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败, 该类型下有产品！", "", "", "", false, "", ""));
            }
            else
            {
                string name = _producttypeAppService.GetById(int.Parse(id)).ProductType_name;
                if (_producttypeAppService.DeleteById(int.Parse(id)))
                {
                    SessionModel sm = getUserSession();
                    _logAppService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.delete, "删除产品类型 " + name);

                    return Content(ReturnJsonHelp.BJUIajaxJson(200, "删除成功！", "ProductType", "", "", false, "", ""));
                }
                else
                {
                    return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败！", "", "", "", false, "", ""));
                }
            }
        }
        #endregion

        #region 软件管理
        /// <summary>
        /// 打开产品管理列表视图
        /// </summary>
        /// <param name="pagemodel"></param>
        /// <returns></returns>
        public IActionResult Index(PageModel pagemodel)
        {
            //获取Session信息并且返回前台
            User userSession = getUserSession().User;
            
                if (string.IsNullOrEmpty(pagemodel.PageCurrent))
                    pagemodel.PageCurrent = "1";
                if (string.IsNullOrEmpty(pagemodel.PageSize))
                    pagemodel.PageSize = "30";
                ViewBag.SearchKeyWords = pagemodel.SearchKeyWords;
                ViewBag.PageSize = pagemodel.PageSize;
                ViewBag.PageCurrent = pagemodel.PageCurrent;
                ViewBag.OrderField = pagemodel.OrderField;
                ViewBag.OrderDirection = pagemodel.OrderDirection;
                ViewBag.AllRecords = _productAppService.GetAll(pagemodel.SearchKeyWords).Count;
                //ViewBag.Modellist = _productAppService.GetPageList(pagemodel.SearchKeyWords, int.Parse(pagemodel.PageSize), int.Parse(pagemodel.PageCurrent), pagemodel.OrderField, pagemodel.OrderDirection);

                List<Product> productlist = _productAppService.GetPageList(pagemodel.SearchKeyWords, int.Parse(pagemodel.PageSize), int.Parse(pagemodel.PageCurrent), pagemodel.OrderField, pagemodel.OrderDirection).ToList();
                List<ProductType> producttypelist = _producttypeAppService.GetAll("");
                ViewBag.Modellist = new CS.vProductHelp().GetVProductList(productlist, producttypelist);
                return View();
            
        }

        /// <summary>
        /// 打开产品编辑视图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Edit(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return View();
            }
            else
            {
                var model = _productAppService.GetById(Int32.Parse(id));
                return View(model);
            }

        }

        /// <summary>
        /// 打开上传视图
        /// </summary>
        /// <returns></returns>
        public IActionResult Upload()
        {
            return View();
        }

        /// <summary>
        /// 上传接口
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost("UploadFiles")]
        public IActionResult UploadFiles(IList<IFormFile> files)
        {
            try
            {
                string logrenark = "";
                long size = 0;

                foreach (var file in files)
                {
                    var filename = ContentDispositionHeaderValue
                                    .Parse(file.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    filename = filename.Substring(filename.LastIndexOf('\\') + 1);
                    logrenark += filename + ",";
                    filename = System.IO.Directory.GetCurrentDirectory() + "/wwwroot/upload/" + filename;
                    size += file.Length;
                    using (FileStream fs = System.IO.File.Create(filename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                }

                SessionModel sm = getUserSession();
                _logAppService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.upload, "上传文件" + logrenark);

                return Content(ReturnJsonHelp.BJUIajaxJson(200, "上传成功！", "", "", "", false, "", ""));
            }
            catch (Exception e)
            {
                return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败！ [" + e.Message + "]", "", "", "", false, "", ""));
            }
        }

        /// <summary>
        /// 表单提交产品编辑接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("ProductEdit")]
        public IActionResult ProductEdit(Product model)
        {

            model.Createtime = DateTime.Now;
            if (_productAppService.AddOrUpdate(model))
            {
                SessionModel sm = getUserSession();
                if (model.Id != 0)
                    _logAppService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.add, "新增产品" + model.Product_name);
                else
                    _logAppService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.update, "修改产品" + model.Product_name);

                return Content(ReturnJsonHelp.BJUIajaxJson(200, "提交成功！", "ProductIndex", "", "", true, "", ""));
            }
            else
            {
                return Content(ReturnJsonHelp.BJUIajaxJson(300, "提交失败！", "", "", "", false, "", ""));
            }

        }

        /// <summary>
        /// 按钮提交删除接口
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult ProductDelete(string id)
        {
            string name = _productAppService.GetById(int.Parse(id)).Product_name;
            if (_productAppService.DeleteById(int.Parse(id)))
            {
                SessionModel sm = getUserSession();
                _logAppService.Add(DateTime.Now, sm.IP, sm.User.Id.ToString(), (int)OperationEnum.delete, "删除产品" + name);

                return Content(ReturnJsonHelp.BJUIajaxJson(200, "删除成功！", "ProductIndex", "", "", false, "", ""));
            }
            else
            {
                return Content(ReturnJsonHelp.BJUIajaxJson(300, "删除失败！", "", "", "", false, "", ""));
            }
        }

        /// <summary>
        /// 打开上传文件选择视图
        /// </summary>
        /// <returns></returns>
        public IActionResult search()
        {
            string jsonstr = "";
            List<fileinfoModel> list = FileUtil.FindFile("wwwroot//upload");
            int i = 0;
            foreach (fileinfoModel m in list)
            {
                jsonstr += "{\"Product_url\":\"" + m.name + "\", \"uploadurl\":\"/wwwroot/upload/" + m.name + "\", \"date\":\"" + m.createtime.ToString("yyyy-MM-dd HH:mm:ss") + "\"},";
                i++;
            }
            if (i > 0)
                return Content("[" + jsonstr.Remove(jsonstr.Length - 1) + "]");
            else
                return Content("[]");
        }

        /// <summary>
        /// 获取类型Json
        /// </summary>
        /// <returns></returns>
        public IActionResult SearchType()
        {
            StringBuilder resultstr = new StringBuilder();
            List<ProductType> list = _producttypeAppService.GetAll("").Where(i => i.Disable == 1).ToList();
            resultstr.Append("[");
            int y = 0;
            foreach (ProductType a in list)
            {
                resultstr.Append("{\"ProductType_Id\":\"" + a.Id + "\",\"ProductType_name\":\"" + a.ProductType_name + "\"},");
                y++;
            }
            if (y > 0)
                resultstr.Remove(resultstr.ToString().LastIndexOf(','), 1);
            resultstr.Append("]");
            return Content(resultstr.ToString());
        }
        #endregion
        
        #endregion

        
    }
}
